package control.character;

import appstate.AISpace;
import com.bulletphysics.collision.dispatch.CollisionObject;
import com.jme3.animation.AnimChannel;
import com.jme3.animation.AnimControl;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.AbstractControl;
import com.jme3.scene.control.CameraControl;
import game.constant.Constants;

public abstract class AbstractAIControl extends AbstractControl implements AIControl {
    protected AISpace aiSpace;
    protected MyCharacterControl characterControl; //it's just easier to keep a copy of this around than to grab it every update

    @Override
    protected void controlUpdate(float tpf) {
	checkForCollisions();
	updateWalkDir();
    }

    protected void checkForCollisions() {
	for(CollisionObject collision : characterControl.getObjectId().getOverlappingPairs()) {
	    if(collision.getUserPointer() != null && collision.getUserPointer() instanceof RigidBodyControl) {
		RigidBodyControl collidingRigidBody = (RigidBodyControl)collision.getUserPointer();
		collideWith((Spatial)collidingRigidBody.getUserObject());
	    }
	}
    }

    protected void updateWalkDir() {
	Vector3f currentWalkDir = spatial.getUserData(Constants.AI_CURRENT_WALK_DIR);
	if(currentWalkDir != null) {
	    characterControl.setWalkDirection(currentWalkDir);

	    //update the camera direction here, for lack of a better place
	    //note: right now, the camera is always set to the direction the ai is walking
	    if(!currentWalkDir.equals(Vector3f.ZERO)) { //exclude a zero vector so we don't face the origin when stopped
		spatial.getControl(CameraControl.class).getCamera().lookAtDirection(currentWalkDir, Vector3f.UNIT_Y);
	    }
	}
    }

    @Override
    protected void controlRender(RenderManager rm, ViewPort vp) {
	//nothing to see here
    }

    @Override
    public void setSpatial(Spatial spatial) {
	super.setSpatial(spatial);
        characterControl = this.spatial.getControl(MyCharacterControl.class);
    }

    public void setRandomWalkDirection() {
	Vector3f newDir = new Vector3f(FastMath.rand.nextFloat(), 0f, FastMath.rand.nextFloat()).normalizeLocal().multLocal((Float)spatial.getUserData(Constants.CHARACTER_CURRENT_SPEED)/100f);
	if(FastMath.rand.nextInt(2) == 1)
	    newDir.setX(newDir.getX()*-1);
	if(FastMath.rand.nextInt(2) == 1)
	    newDir.setZ(newDir.getZ()*-1);
	this.spatial.setUserData(Constants.AI_CURRENT_WALK_DIR, newDir);
    }

    public void setAISpace(AISpace space) {
        aiSpace = space;
    }

    public AISpace getAISpace() {
	return aiSpace;
    }
}
